<template>
<div>
    <!-- 面包屑组件 -->
    <breadcrumb :nav-data="['商品管理','添加商品']"></breadcrumb>
     <el-card>
        <!-- Alert 警告 -->
        <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>

        <!-- Steps 步骤条 -->
        <el-steps style="margin:20px auto;" finish-status="success" :active="Number(active)" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>

        <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-position="top">
            <!-- Tabs 标签页 -->
            <el-tabs tab-position="left" v-model="active" :before-leave="tabChange" @tab-click="onTabClick">
                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="addForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="goods_price">
                        <el-input v-model.number="addForm.goods_price"></el-input>
                    </el-form-item>
                    <el-form-item label="商品重量" prop="goods_weight">
                        <el-input v-model.number="addForm.goods_weight"></el-input>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="goods_number">
                        <el-input v-model.number="addForm.goods_number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="goods_cat">
                        <!--级联选择器-->
                        <el-cascader
                        v-model="addForm.goods_cat"
                        @change="onCascaderChange"
                        :options="cascaderOptions"
                        :props="cascaderProps"></el-cascader>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                        <el-checkbox-group v-model="item.attr_vals" size="small">
                            <el-checkbox v-for="(it,ind) in item.attr_values" :key="ind" :label="it" border></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                   
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
                        <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <el-upload
                        :on-success="onSuccessful"
                        :action="$http.defaults.baseURL+'/upload'"
                        :headers="headers"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <!-- 富文本编辑器 -->
                    <quill-editor v-model="addForm.goods_introduce">
                    </quill-editor>

                    <!-- 添加按钮 -->
                    <el-button class="addBtn" type="primary" @click="onAddGoods">添加商品</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-form>
     </el-card>
</div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      //分类级联选择器
      cascaderOptions: [],
      //分类级联选择器配置项
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },

      active: 0,
      //添加商品表单
      addForm: {
        goods_name: "", //商品名称
        goods_price: 0, //价格
        goods_weight: 0, //重量
        goods_number: 0, //数量
        goods_cat: [], //分类
        goods_introduce: "", //商品内容
        pics: [], //上传的图片临时路径
        attrs: [] //商品的参数（数组），包含 `动态参数` 和 `静态属性`
      },
      //表单规则验证
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 1, max: 15, message: "长度在 1 到 15 个字符", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          { type: "number", message: "商品价格必须为数字值" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
          { type: "number", message: "商品重量必须为数字值" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
          { type: "number", message: "商品数量必须为数字值" }
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" }
        ]
      },

      //商品动态参数数据
      manyTableData: [],
      //商品静态属性数据
      onlyTableData: [],

      //图片预览弹窗 图片地址
      dialogImageUrl: "",
      //图片预览弹窗隐藏显示
      dialogVisible: false,
      //上传图片插件请求头
      headers: {
        Authorization: window.sessionStorage.getItem("token")
      }
    };
  }, // 组件方法
  created() {
    this.getCategoriesData();
  },
  methods: {
    //获取分类数据
    async getCategoriesData() {
      let res = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cascaderOptions = res.data;
    },
    //分类级联选择器change事件
    onCascaderChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        return this.$message.warning("只能选择三级商品分类！");
      }
    },

    //切换tab之前做的事
    tabChange(activeName, oldActiveName) {
      console.log(oldActiveName, activeName);
      if (oldActiveName == 0) {
        if (!this.addForm.goods_name)
          return Promise.reject(this.$message.error("请先填写商品名称！"));
        if (this.addForm.goods_cat.length !== 3) {
          return Promise.reject(this.$message.error("请先选择商品分类！"));
        }
      }
    },

    //点击tab栏时
    onTabClick() {
      switch (this.active) {
        case "1": {
          this.getCateData("many");
          break;
        }
        case "2": {
          this.getCateData("only");
          break;
        }
      }
    },
    //获取分类数据
    async getCateData(selStr) {
      if (this[selStr + "TableData"].length !== 0) return;
      let res = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: selStr
        }
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      if (selStr === "many") {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          item.attr_values = JSON.parse(JSON.stringify(item.attr_vals));
        });
      }
      this[selStr + "TableData"] = res.data;
    },

    //移除已上传图片的回调函数
    handleRemove(file, fileList) {
      console.log(file, fileList);
      //获取要删除图片的临时路径
      let filePath = file.response.data.tmp_path;
      //获取临时路径找图片的索引
      let deleteIndex = this.addForm.pics.findIndex(
        item => item.pic === filePath
      );
      //删除
      this.addForm.pics.splice(deleteIndex, 1);
    },
    //点击预览图片回调函数
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片上传成功后的钩子
    onSuccessful(response) {
      console.log(response, "图片上传");
      this.addForm.pics.push({
        pic: response.data.tmp_path
      });
    },

    //点击添加商品
    async onAddGoods() {
      let goodsForm = JSON.parse(JSON.stringify(this.addForm));
      goodsForm.goods_cat = goodsForm.goods_cat.join(",");
      console.log(goodsForm.goods_cat,'goodsForm.goods_cat');
      console.log(this.manyTableData,this.onlyTableData,'动静态');
      //处理动态参数
      this.manyTableData.forEach(item => {
        goodsForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(",")
        });
      });
      //处理静态属性
      this.onlyTableData.forEach(item => {
        goodsForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        });
      });
      console.log(goodsForm, "goodsForm");
      //向后端发起请求
      let res = await this.$http.post("/goods",goodsForm);
      console.log(res,'add_goods==>res');
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.$router.push("/goods");
    }
  },

  computed: {
    //三级分类id
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    }
  }
};
</script> 

<style  lang='scss'>
.el-step__title {
  font-size: 12px;
}
.addBtn {
  margin-top: 20px;
}
</style>